<script lang="tsx" setup>
/**
 * 渲染列表
 */
import {ref, watch} from "vue"
import FormDetail from "./components/form-detail/index.vue"

/**
 * 定义props
 */
const props = defineProps<{
  els: any[]
}>()

/**
 * 定义emit
 */
const emit = defineEmits<{
  (e: "add"): void
  (e: "change", data: any): void
}>()

/**
 * 数据
 */
const elsData: any = ref([])

/**
 * 添加
 */
const handleAdd = () => {
  elsData.value.push({
    label: "",
    prop: ""
  })
  emit("change", elsData.value)
}

/**
 * 编辑
 */
const formDetailRef = ref()
const handleEdit = (index: number) => {
  formDetailRef.value.show({
    data: elsData.value[index],
    index: index
  })
}

/**
 * 删除
 */
const handleDelete = (index: number) => {
  elsData.value.splice(index, 1)
  emit("change", elsData.value)
}

/**
 * 确认
 */
const handleConfirm = (params: { data: any, index: number }) => {
  elsData.value[params.index] = params.data
  emit("change", elsData.value)
}

/**
 * 监视
 */
watch(() => props.els, (newValue) => {
  if (newValue) {
    elsData.value = newValue
  }
}, {
  deep: true
})

handleAdd()
</script>

<template>
  <div class="els-form">
    <div class="list">
      <div v-for="(item,index) in elsData" :key="index" class="item">
        <div class="item-input">
          <el-input v-model="item.label" clearable placeholder="名称" size="small"/>
        </div>
        <div class="item-input">
          <el-input v-model="item.prop" clearable placeholder="数据key" size="small"/>
        </div>
        <div class="item-button">
          <el-button link size="small" type="primary" @click="handleEdit(index)">编辑</el-button>
        </div>
        <div class="item-button">
          <el-button link size="small" type="primary" @click="handleDelete(index)">删除</el-button>
        </div>
      </div>
    </div>
    <div class="form-add" @click="handleAdd">
      +
    </div>

    <!-- 详情数据 -->
    <FormDetail ref="formDetailRef" @confirm="handleConfirm"/>
  </div>
</template>

<style lang="scss" scoped>
.els-form {
  .list {
    .item {
      display: flex;

      .item-input {
        margin-right: 10px;
      }
    }
  }

  .form-add {
    color: #666;
    cursor: pointer;
    margin: 10px auto 0 auto;
    width: 100px;
    height: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid #ccc;
    border-radius: 5px;
  }
}
</style>